import { cloneDeep } from 'lodash'

export default {
  /**
   * 数组转树结构
   * @param {any} dataList        数组数据
   * @param {*} key               节点唯一标识
   * @param {*} parentKey         上级节点标识
   * @param {string} childrenKey  下级节点名称
   * @returns
   */
  toTree (dataList = [], key, parentKey, childrenKey = 'children') {
    const nodeList = cloneDeep(dataList), nodeMap = {}
    nodeList.map((data, index) => {
      nodeMap[data[key]] = data
    })
    nodeList.map((node) => {
      const parentNode = nodeMap[node[parentKey]]
      if (parentNode) {
        parentNode[childrenKey] = parentNode[childrenKey] || []
        parentNode[childrenKey].push(node)
        node._parent = parentNode
      }
    })
    const treeNodes = []
    // 获取根节点
    nodeList.map(item => {
      if (!item._parent) {
        treeNodes.push(item)
      }
    })
    return { nodeList: treeNodes, nodeMap }
  },
  /**
   * 树形结构转Map
   * @param {*} key    唯一标识
   * @param {*} dataList    树形结构数据
   * @param {*} childrenKey 下级节点字段
   * @returns
   */
  treeToMap (dataList = [], key, childrenKey = 'children') {
    const map = {}
    dataList.map(data => {
      _treeToMap(data, key, childrenKey, map)
    })
    return map
  },
  /**
   * 获取树形结构指定节点的所有上级节点
   * @param {*} data  树节点
   */
  getParents (data, reverse = true) {
    const list = []
    let p = data._parent
    while (p) {
      list.push(p)
      p = p._parent
    }
    return reverse ? list.reverse() : list
  },
  /**
   * 扁平化树结构
   * @param {*} dataList 树形结构数据
   */
  flat (dataList = [], childrenKey = 'children', level = 0) {
    const list = []
    dataList.map((data, index) => {
      _flat(data, list, childrenKey, null, index + level)
    })
    return list
  }
}

function _treeToMap (data, key, childrenKey, map) {
  map[data[key]] = data
  data[childrenKey]?.map(child => {
    _treeToMap(child, key, childrenKey, map)
  })
}

function _flat (data, list, childrenKey, parent, level) {
  list.push(data)
  data._level = `${level}`
  parent && (data._parent = parent) && (data._level = `${parent._level}/${data._level}`)
  data[childrenKey]?.map((item, index) => {
    _flat(item, list, childrenKey, data, level + index)
  })
}

function dataToMap (data) {

}